package com.example.wm.SanWar.controller;
import com.example.wm.SanWar.VO.AliianceStatictogetherAll;
import com.example.wm.SanWar.VO.MemberStaticVo;
import com.example.wm.SanWar.entity.*;
import com.example.wm.SanWar.mapper.AlliesandUserMapper;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.wm.SanWar.VO.Allistatic2Vo;
import com.example.wm.SanWar.VO.AllstaticsVo;
import com.example.wm.SanWar.service.AllianceStatisticsDetailService;
import com.example.wm.SanWar.service.AllianceStatisticsService;
import com.example.wm.SanWar.service.AlliesRecodeSheetService;
import com.example.wm.common.Result;
import com.example.wm.common.ResultData;
import com.example.wm.utils.TsyUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/AllianceStatisticsController")
public class AllianceStatisticsController {
    @Resource
    private AllianceStatisticsService allianceStatisticsService;
    @Resource
    private TsyUtils tsyUtils;
    @Resource
    private AlliesRecodeSheetService alliesRecodeSheetService;
    @Resource
    private AllianceStatisticsDetailService allianceStatisticsDetailService;
    @Resource
    private AlliesandUserMapper alliesandUserMapper;

    @Transactional
    @PostMapping("/Insert")
    public Result Insert(@RequestBody AllianceStatistics allianceStatistics) {
        allianceStatistics.setCreatetime(tsyUtils.getnowtime());
        boolean b=    allianceStatisticsService.save(allianceStatistics);
        if(b){
            Integer id= allianceStatistics.getId();
            alliesRecodeSheetService.insertList(allianceStatistics.getName(),"上传了考勤表");
            return ResultData.success(id);
        }else{
            return ResultData.error(403,"失败");

        }
    }
    @Transactional
    @PostMapping("/InsertDetail")
    public Result InsertDetail(@RequestBody AllianceStatisticsDetails allianceStatisticsDetails) {
        try {
            boolean b=    allianceStatisticsDetailService.save(allianceStatisticsDetails);
            if(b){


                return ResultData.success(b);

            }else{

                return ResultData.error(403,"失败");

            }
        } catch (DataIntegrityViolationException e) {
            log.error("插入数据失败: {}", e.getMessage(), e);
            throw e;
        }

    }
    @Transactional
    @PostMapping("/findbytime")
    public Result findbytime(@RequestBody AllianceStatistics allianceStatistics) {
        LambdaQueryWrapper<AllianceStatistics> lq=new LambdaQueryWrapper<>();
        lq.eq(AllianceStatistics::getTime1,allianceStatistics.getTime1());
        lq.eq(AllianceStatistics::getTime2,allianceStatistics.getTime2());
        lq.eq(AllianceStatistics::getCreateid,allianceStatistics.getCreateid());
        lq.eq(AllianceStatistics::getMinMillitary,allianceStatistics.getMinMillitary());


        Long n=  allianceStatisticsService.count(lq);
        if(n>0){


            return ResultData.error(304,"已存在");

        }else{
            return ResultData.success("未存在");

        }
    }

    @Transactional
    @PostMapping("/findbytimenumber")
    public Result findbytimenumber(@RequestBody JSONObject jsonObject) {
//        System.out.println(allianceStatistics+"allianceStatistics");


        // 创建指定年份和月份的 LocalDate 对象
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();

        // 获取当前年份
        int currentYear = currentDate.getYear();
        LocalDate specifiedDate = Year.of(currentYear).atMonth(jsonObject.getInteger("num")).atDay(1);
        int currentYear2 = currentDate.getYear()-1;
        // 计算该月份的最后一天
        int lastDayOfMonth = specifiedDate.with(TemporalAdjusters.lastDayOfMonth()).getDayOfMonth();
        // 创建起始和结束日期的 LocalDateTime 对象
        LocalDateTime startDate = LocalDate.of(currentYear, jsonObject.getInteger("num"), 1).atTime(LocalTime.MIDNIGHT);
        LocalDateTime endDate = LocalDate.of(currentYear, jsonObject.getInteger("num"), lastDayOfMonth).atTime(LocalTime.of(23, 59, 59));
       // 创建起始和结束日期的 LocalDateTime 对象
        LocalDateTime startDate2 = LocalDate.of(currentYear2, jsonObject.getInteger("num"), 1).atTime(LocalTime.MIDNIGHT);
        LocalDateTime endDate2 = LocalDate.of(currentYear2, jsonObject.getInteger("num"), lastDayOfMonth).atTime(LocalTime.of(23, 59, 59));
        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 将 LocalDateTime 转换为字符串
        String startDateStr = startDate.format(formatter);
        String endDateStr = endDate.format(formatter);
        String startDateStr2 = startDate2.format(formatter);
        String endDateStr2 = endDate2.format(formatter);
        // 将字符串转换为 LocalDateTime
//        LocalDateTime startDates = LocalDateTime.parse(startDateStr, formatter);
//        LocalDateTime endDates = LocalDateTime.parse(endDateStr, formatter);
//        LocalDateTime startDates2 = LocalDateTime.parse(startDateStr2, formatter);
//        LocalDateTime endDates2 = LocalDateTime.parse(endDateStr2, formatter);
        LambdaQueryWrapper<AllianceStatistics> lq=new LambdaQueryWrapper<>();
        lq.eq(AllianceStatistics::getCreateid,jsonObject.getString("createid"));
        lq.between(AllianceStatistics::getTime1, startDateStr, endDateStr);


        LambdaQueryWrapper<AllianceStatistics> lq2=new LambdaQueryWrapper<>();
        lq2.eq(AllianceStatistics::getCreateid,jsonObject.getString("createid"));
        lq2.between(AllianceStatistics::getTime1, startDateStr2, endDateStr2);
        ArrayList<AllianceStatistics> arrayList=new ArrayList<>();

        if(allianceStatisticsService.count(lq)>0 ||  allianceStatisticsService.count(lq2)>0 ){
            List<AllianceStatistics> la=  allianceStatisticsService.list(lq);
            List<AllianceStatistics> la2=  allianceStatisticsService.list(lq2);

            if(!la.isEmpty()){
                arrayList.addAll(la);
            }
            if(!la2.isEmpty()){
                arrayList.addAll(la2);
            }
            for (AllianceStatistics allianceStatistics : arrayList) {
                //查询姓名
                LambdaQueryWrapper<AlliesandUser> lqg=new LambdaQueryWrapper<>();
                lqg.eq(AlliesandUser::getId,allianceStatistics.getCreateid());
                AlliesandUser all=alliesandUserMapper.selectOne(lqg);
                allianceStatistics.setName(all.getName());

            }

            return ResultData.success(arrayList);
        }else{
            return ResultData.error(304,"未找到");

        }
    }
    @Transactional
    @PostMapping("/clearall")
    public Result clearall(@RequestBody AllianceStatisticsDetails allianceStatisticsDetails) {
        LambdaQueryWrapper<AllianceStatisticsDetails> lq=new LambdaQueryWrapper<>();
        lq.eq(AllianceStatisticsDetails::getType,allianceStatisticsDetails.getType());

        List<AllianceStatisticsDetails> al=allianceStatisticsDetailService.list(lq);
        allianceStatisticsDetailService.removeBatchByIds(al);

        return ResultData.success("全部删除成功");


    }
    @Transactional
    @PostMapping("/getallstatics")
    public Result getallstatics(@RequestBody AlliesandUser alliesandUser) {
        AllstaticsVo avo=new AllstaticsVo();
        LambdaQueryWrapper<AllianceStatisticsDetails> lq=new LambdaQueryWrapper<>();
//        lq.eq(AlliesandUser::getTmid,alliesandUser.getId());
//        lq.eq(AlliesandUser::getStatus,"在盟");
//        List<AlliesandUser> alist=alliesandUserService.list(lq);
        //1.总人数
        lq.eq(AllianceStatisticsDetails::getTmtjid,alliesandUser.getId())
          .eq(AllianceStatisticsDetails::getType,"2");
       Long num=  allianceStatisticsDetailService.count(lq);
        List<AllianceStatisticsDetails> alist=allianceStatisticsDetailService.list(lq);

        avo.setNumberpp(Math.toIntExact(num));
          //2.新增加用户
        LambdaQueryWrapper<AllianceStatisticsDetails> lq2=new LambdaQueryWrapper<>();
        lq2.eq(AllianceStatisticsDetails::getTmtjid,alliesandUser.getId()) .eq(AllianceStatisticsDetails::getType,"1");
        List<AllianceStatisticsDetails> alist2=allianceStatisticsDetailService.list(lq2);

        // 获取 alist 中的成员集合
        Set<String> existingMembers = alist.stream()
                .map(AllianceStatisticsDetails::getName)
                .collect(Collectors.toSet());

       // 获取 alist2 中的新增用户
        List<AllianceStatisticsDetails> newDataList = alist2.stream()
                .filter(item -> !existingMembers.contains(item.getName()))
                .collect(Collectors.toList());
        avo.setNewDataList(newDataList);
        // 获取 alist 中存在但 alist2 中不存在的对象 退盟用户
        Set<String> membersInAlist2 = alist2.stream()
                .map(AllianceStatisticsDetails::getName)
                .collect(Collectors.toSet());

        List<AllianceStatisticsDetails> objectsInAlistNotInAlist2 = alist.stream()
                .filter(item -> !membersInAlist2.contains(item.getName()))
                .collect(Collectors.toList());
        avo.setObjectsInAlistNotInAlist2(objectsInAlistNotInAlist2);





        return ResultData.success(avo);
    }


    @Transactional
    @PostMapping("/getallstatics2")
    public Result getallstatics2(@RequestBody AlliesandUser alliesandUser) {
        Allistatic2Vo vo=new Allistatic2Vo();
        LambdaQueryWrapper<AllianceStatisticsDetails> lq=new LambdaQueryWrapper<>();
        lq.eq(AllianceStatisticsDetails::getTmtjid,alliesandUser.getId())
                .eq(AllianceStatisticsDetails::getType,"1");
        Long num=  allianceStatisticsDetailService.count(lq);
        List<AllianceStatisticsDetails> alist=allianceStatisticsDetailService.list(lq);
         vo.setDataList1(alist);

        LambdaQueryWrapper<AllianceStatisticsDetails> lq2=new LambdaQueryWrapper<>();
        lq2.eq(AllianceStatisticsDetails::getTmtjid,alliesandUser.getId())
                .eq(AllianceStatisticsDetails::getType,"2");
        Long num2=  allianceStatisticsDetailService.count(lq2);
        List<AllianceStatisticsDetails> alist2=allianceStatisticsDetailService.list(lq2);

        vo.setDataList2(alist2);



        return ResultData.success(vo);
    }

    //请求服务器
    @Transactional
    @PostMapping("/getallstatics3")
    public Result requestorc(@RequestBody JSONObject jsonObject) throws JsonProcessingException {
        RestTemplate restTemplate = new RestTemplate();
        // 创建请求头
//        HttpHeaders headers = new HttpHeaders();
//        MediaType mediaType = MediaType.parseMediaType("application/json;charset=utf-8");
//        headers.setContentType(mediaType);
// 创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        // 创建请求体

// 创建请求体
        Map<String, Object> requestData = new HashMap<>();
        requestData.put("queryType", "存储过程");
        requestData.put("queryName", jsonObject.getString("queryName"));
        requestData.put("minBattlePoints", jsonObject.getInteger("minBattlePoints"));
        requestData.put("id", jsonObject.getString("id"));



        ObjectMapper objectMapper = new ObjectMapper();
        String requestJson = objectMapper.writeValueAsString(requestData);

        HttpEntity<String> request = new HttpEntity<>(requestJson, headers);
        String url="http://118.31.75.80:3000/api/query";
        String response = restTemplate.postForObject(url, request, String.class);




        System.out.println("Response: " + response);
        return ResultData.success(response);
    }


    @Transactional
    @PostMapping("/reqexcel")
    public Result reqexcel(@RequestBody JSONObject jsonObject) throws IOException, InterruptedException {

        RestTemplate restTemplate = new RestTemplate();

        // 创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);


      // 创建请求体
        Map<String, Object> requestData = new HashMap<>();
        requestData.put("queryType", "存储过程");
        requestData.put("queryName", jsonObject.getString("queryName"));
        requestData.put("minBattlePoints", jsonObject.getInteger("minBattlePoints"));
        requestData.put("id", jsonObject.getString("id"));
        requestData.put("columns", jsonObject.getString("columns"));

        ObjectMapper objectMapper = new ObjectMapper();
        String requestJson = objectMapper.writeValueAsString(requestData);

        HttpEntity<String> request = new HttpEntity<>(requestJson, headers);
        String url="http://118.31.75.80:3000/api/export";
        String response = restTemplate.postForObject(url, request, String.class);
        // 假设响应是一个JSON，包含下载URL
        JsonNode jsonNode = objectMapper.readTree(response);
        String downloadUrl = jsonNode.get("downloadUrl").asText();
         System.out.println("downloadUrl"+downloadUrl);
        // 使用Java 11的HttpClient下载文件
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request2 = HttpRequest.newBuilder()
                .uri(URI.create("http://118.31.75.80:3000"+downloadUrl))
                .build();

        HttpResponse<byte[]> response2 = client.send(request2, HttpResponse.BodyHandlers.ofByteArray());
        byte[] fileBytes = response2.body();
        System.out.println("Response: " + response);
        return ResultData.success(fileBytes);
    }

    @Transactional
    @PostMapping("/reqexcelgeturl")
    public Result reqexcelgeturl(@RequestBody JSONObject jsonObject) throws IOException, InterruptedException {

        RestTemplate restTemplate = new RestTemplate();

      // 创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        // 创建请求体
        Map<String, Object> requestData = new HashMap<>();
        requestData.put("queryType", "存储过程");
        requestData.put("queryName", jsonObject.getString("queryName"));
        requestData.put("minBattlePoints", jsonObject.getInteger("minBattlePoints"));
        requestData.put("id", jsonObject.getString("id"));
        requestData.put("columns", jsonObject.getString("columns"));

        ObjectMapper objectMapper = new ObjectMapper();
        String requestJson = objectMapper.writeValueAsString(requestData);
        HttpEntity<String> request = new HttpEntity<>(requestJson, headers);
        String url="http://118.31.75.80:3000/api/export";
        String response = restTemplate.postForObject(url, request, String.class);

        // 假设响应是一个JSON，包含下载URL
        JsonNode jsonNode = objectMapper.readTree(response);
        String downloadUrl = jsonNode.get("downloadUrl").asText();
        System.out.println("downloadUrl"+downloadUrl);
        System.out.println("Response: " + response);
        return ResultData.success("http://118.31.75.80:3000"+downloadUrl);
    }

    @Transactional
    @PostMapping("/toexcel2")
    public Result toexcel2(@RequestBody List<AliianceStatictogetherAll> aliianceStatictogetherAllList) throws IOException, InterruptedException {
        try (Workbook workbook = new XSSFWorkbook()) {
            int numbers=7;
            Sheet sheet = workbook.createSheet("组别数据");
            createDoubleHeaderRow(sheet, aliianceStatictogetherAllList,numbers);
            int rowIndex ;
            int index=1;

            for (int i = 0; i < aliianceStatictogetherAllList.size(); i++) {
                rowIndex=2;
                for (MemberStaticVo member : aliianceStatictogetherAllList.get(i).getList()) {
                    Row row = sheet.getRow(rowIndex) != null ? sheet.getRow(rowIndex++) : sheet.createRow(rowIndex++);
                    createDataRow(sheet,row, member,index+numbers*i);
                }
            }

            // 确保表头列宽设置生效

            setColumnWidths(sheet, aliianceStatictogetherAllList,numbers);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            workbook.write(baos);
            return ResultData.success(baos.toByteArray());
        }



    }




    private void setColumnWidths(Sheet sheet, List<AliianceStatictogetherAll> groups,int number) {
        int columnIndex = 1;
        for (AliianceStatictogetherAll group : groups) {
            for (int i = 0; i <= number-1; i++) {
                sheet.setColumnWidth(columnIndex + i, 256 * 10); // 20个字符宽度
            }
            columnIndex += number;
        }
    }

    private void createDoubleHeaderRow(Sheet sheet, List<AliianceStatictogetherAll> groups,int numbers) {
        Row mainHeaderRow = sheet.createRow(0);
        Row subHeaderRow = sheet.createRow(1);



        int columnIndex = 1;
        int index=1;


   List<Short> colorList=new ArrayList<>();

        colorList.add(  IndexedColors.GREEN.getIndex());
        colorList.add(IndexedColors.SKY_BLUE.getIndex());
        colorList.add( IndexedColors.YELLOW.getIndex());
        colorList.add( IndexedColors.GREY_25_PERCENT.getIndex());
        colorList.add(IndexedColors.ORANGE.getIndex());
        colorList.add( IndexedColors.TURQUOISE.getIndex());
        colorList.add( IndexedColors.VIOLET.getIndex());
        colorList.add( IndexedColors.PINK.getIndex());
        colorList.add( IndexedColors.GREY_40_PERCENT.getIndex());




        // 合并格子

        for (AliianceStatictogetherAll group : groups) {

            sheet.addMergedRegion(new CellRangeAddress(0, 0, columnIndex+2, columnIndex + numbers-1));
            mainHeaderRow.createCell(columnIndex+2).setCellValue(group.getName());
            CellStyle mainHeaderStyle = createHeaderStyle(sheet.getWorkbook(), colorList.get(index));
            CellStyle subHeaderStyle = createSubHeaderStyle(sheet.getWorkbook(),colorList.get(index));
            mainHeaderRow.getCell(columnIndex+2).setCellStyle(mainHeaderStyle);

            if(index>7){
                index=1;
            }else {
                index++;
            }


            // 创建子表头
//            subHeaderRow.createCell(1+columnIndex).setCellValue("分组");
            subHeaderRow.createCell(2+columnIndex).setCellValue("成员");
            subHeaderRow.createCell(3+columnIndex).setCellValue("缺勤次数");
            subHeaderRow.createCell(4+columnIndex).setCellValue("势力值差值");

            subHeaderRow.createCell(5+columnIndex).setCellValue("战功差值");
            subHeaderRow.createCell(6+columnIndex).setCellValue("状态");
//            subHeaderRow.createCell(7+columnIndex).setCellValue("表1势力值");
//            subHeaderRow.createCell(8+columnIndex).setCellValue("表1战功总量");
//            subHeaderRow.createCell(9+columnIndex).setCellValue("表2势力值");
//            subHeaderRow.createCell(10+columnIndex).setCellValue("表2战功总量");
//
            for (int i = 2+columnIndex; i < numbers+columnIndex; i++) {
                subHeaderRow.getCell(i).setCellStyle(subHeaderStyle);
            }
            columnIndex += numbers;


        }




    }

    private void createDataRow(Sheet sheet,Row row, MemberStaticVo member, int log) {
//        row.createCell(1+log).setCellValue(member.get分组());
               row.createCell(2+log).setCellValue(member.get成员());
               row.createCell(3+log).setCellValue(member.get缺勤次数());
//               if(member.get势力值差值()<0){
//                   row.createCell(4+log).setCellValue(member.get势力值差值());
//                   row.getCell(4+log).setCellStyle(createcellStyle(sheet.getWorkbook()));
//
//               }else{
                   row.createCell(4+log).setCellValue(member.get势力值差值());

//               }
               row.createCell(5+log).setCellValue(member.get战功差值());
               row.createCell(6+log).setCellValue(member.get状态());
//               row.createCell(7+log).setCellValue(member.get表1势力值());
//               row.createCell(8+log).setCellValue(member.get表1战功总量());
//               row.createCell(9+log).setCellValue(member.get表2势力值());
//               row.createCell(10+log).setCellValue(member.get表2战功总量());



    }

    private CellStyle createHeaderStyle(Workbook workbook, short color) {
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setBold(true);
        font.setColor(IndexedColors.BLACK.getIndex());
        style.setFillForegroundColor(color);
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
//        style.setBorderTop(BorderStyle.THIN);
//        style.setBorderBottom(BorderStyle.THIN);
//        style.setBorderLeft(BorderStyle.THIN);
//        style.setBorderRight(BorderStyle.THIN);
        style.setFont(font);
        return style;
    }

    private CellStyle createSubHeaderStyle(Workbook workbook, Short color) {
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setBold(true);
        font.setColor(IndexedColors.BLACK.getIndex());
        style.setFillForegroundColor(color);
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
//        style.setBorderTop(BorderStyle.THIN);
//        style.setBorderBottom(BorderStyle.THIN);
//        style.setBorderLeft(BorderStyle.THIN);
//        style.setBorderRight(BorderStyle.THIN);
        style.setFont(font);
        return style;
    }

    private CellStyle createcellStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
//        font.setBold(true);
        font.setColor(IndexedColors.RED.getIndex());
        style.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
//        style.setAlignment(HorizontalAlignment.CENTER);
//        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setFont(font);
        return style;
    }

}
